package fun.tan90.easy.binlog.plugin.mysql.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.zaxxer.hikari.HikariDataSource;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.mysql.listener.MysqlEventProcessor;
import fun.tan90.easy.binlog.plugin.common.listener.CaffeineRemovalListener;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import fun.tan90.easy.binlog.plugin.mysql.service.impl.MysqlPluginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.TimeUnit;

/**
 * description
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/07/13 13:02
 */
@Slf4j
public class MysqlPluginAutoConfiguration {

    public MysqlPluginAutoConfiguration() {
        log.info("init MysqlPlugin");
    }

    @Bean
    public MysqlClientCacheLoader mysqlClientCacheLoader() {
        return new MysqlClientCacheLoader();
    }

    @Bean
    public LoadingCache<String, HikariDataSource> mysqlClientCache(MysqlClientCacheLoader mysqlClientCacheLoader) {
        return Caffeine.newBuilder()
                .maximumSize(10_000)
                .removalListener(new CaffeineRemovalListener(OutputTypeEnum.MYSQL.getOutput()))
                .expireAfterAccess(1, TimeUnit.DAYS)
                .build(mysqlClientCacheLoader);
    }

    @Bean
    public MysqlEventProcessor mysqlEventProcessor(LoadingCache<String, HikariDataSource> mysqlClientCache) {
        return new MysqlEventProcessor(mysqlClientCache);
    }

    @Bean(name = "mysql")
    public PluginService mysqlPluginService() {
        return new MysqlPluginService();
    }
}
